var router = require('koa-router')();
const querystring = require('querystring');
const crypto = require('crypto');

router.get('/wx', function *(next) {
  const url = this.request.url.split('?')[1]
  const query = querystring.parse(url)
  console.log('url:', url, ' query', query)
  const { signature, timestamp, nonce, echostr } = query;
  const token = 'wxapi';
  const tmpArr = [token, timestamp, nonce];
  const tmpStr = tmpArr.sort().join('');
  const sha1 = crypto.createHash('sha1');
  sha1.update(tmpStr);
  const res = sha1.digest('hex');
  console.log('res', res, ' signature', signature)
  if (res === signature) {
    return this.body = echostr;
  }
  return this.body = 'error'
});


module.exports = router;
